<template>
  <div class="superBox">
    <div class="superMain mgt-30 max_w-1200">
      <div style="width: 100%" class="mgb-20">
        <Title></Title>
      </div>
      <div class="flex-s-between">
        <div style="width: 45%" v-if="JSON.stringify(infoData) !== '{}'">
          <div>
            <art-info :infoData="infoData"></art-info>
          </div>
          <div class="border-r bg-47 border-1 mgt-10 boxS-i-4">
            <div v-if="isSell" class="font-26 fontW-7 font-f-ib color-af47 bd-b-1 pdtb-10">
              <interval :date="countdownData"/>
            </div>
            <!-- 特点 -->
            <div class="flex mg-2">
              <div class="flex-1">
                <div class="color-af47 font-14 fontW-7 font-f-ib">{{ $t("detail.trait")}}</div>
                <p class="font-14 fontW-4 font-f-ib color-f mgt-10"
                    v-for="(item, i) in characteristic" :key="i">{{ item.trait_type }}
                    <span class="mgl-13">{{item.value}}</span></p>
                <!-- <div>
                  <div class="font-14 fontW-4 font-f-ib color-f mgt-10"
                    v-for="(item, i) in decoded" :key="i">
                    <div>{{ item.trait_type }}</div>
                    <div class="mgl-13">{{item.value}}</div>
                  </div>
                </div> -->
              </div>
              <!-- <div class="flex-1">
                <span class="color-af47 font-14 font-f-ib fontW-7">{{$t("detail.grade")}}</span>
                <p class="font-14 fontW-4 font-f-ib color-f mgt-10">{{ $t("detail.super") }}<span class="mgl-13">23/100</span></p>
                <p class="font-14 fontW-4 font-f-ib color-f mgt-10">{{ $t("detail.Motivation") }}<span class="mgl-13">11/100</span></p>
              </div> -->
            </div>
          </div>
          <div>
            <!-- 描述 -->
            <div class="border-r bg-47 border-1 mgt-10 boxS-i-4 pd-20" style="min-height:140px">
              <p class="color-af47 fontW-7 font-20 font-f-ib">{{ $t("detail.describe") }}</p>
              <div class="describe_p  color-f fontW-7 font-18 mg-10 font-f-ib" v-if="showDesc">{{description}}</div>
              <el-input v-else class="mgt-10 textBox" type="textarea"
              :autosize="{ minRows: 2, maxRows: 3 }"
              v-model="description" resize="none" ref="inputRef"
              @blur="changeDescBlur"></el-input>
            </div>
          </div>
        </div>
        <!-- <div style="width: 45%" v-if="JSON.stringify(infoData) !== '{}'">
          <info
            :showDesc="showDesc"
            :infoData="infoData"
            @onAndOff="onAndOff"
          />
        </div> -->
        <div class="rightBox" style="width: 42%">
          <div class="imgItem border-1 border-r pd-20 center_a"
            v-if="JSON.stringify(infoData) !== '{}'"
          >
            <img class="bd-r-10" :src="infoData.image_url" alt="" style="width: 100%"/>
          </div>
          <div class="btn flex-s-between">
            <el-button
              type="primary"
              class="bg-f color-0 font-f-ib font-26 fontW-7 mgr-20 btnHove"
              @click="edit"
              v-if="ownerFlag && showDesc"
              >{{ $t("btn.edit") }}</el-button
            >
            <el-button
              type="primary"
              class="bg-f color-0 font-f-ib font-26 fontW-7 mgr-20 btnHove"
              @click="confirm"
              v-if="ownerFlag && !showDesc"
              >{{ $t("btn.confirm") }}</el-button
            >
            <!-- 出售按钮 -->
            <el-button v-if="ownerFlag && !isSell"
              type="primary"
              class="color-0 font-f-ib font-26 fontW-7 btnHove bg-af47"
              @click="hundleSellSubmit"
              >{{ $t("detail.status") }}</el-button
            >
          </div>
        </div>
      </div>
      <p class="font-25 fontW-7 font-f-ib color-af47 pdl-35 mgt-20">{{$t('title.history_bids')}}</p>
      <offer :offerData="offerData" />
      <p class="font-25 fontW-7 font-f-ib color-af47 pdl-35 mgt-20">{{$t('title.vitality')}}</p>
      <activity :activityData="activityData" />
    </div>
  </div>
</template>
<script>
import {initWeb3, initContract} from '../../../static/contract/createContract'
import contractAddress from '../../../static/contract/contractAddress'
import Info from '../../components/component/Info'
import ArtInfo from '../../components/component/ArtInfo'
import Interval from '../../components/component/Interval'
import Offer from '../../components/component/Offer'
import Activity from '../../components/component/Activity'
import Title from '../../components/component/Title'
import { offerData, activityData } from '../../mock/data'

export default {
  components: {
    Info,
    ArtInfo,
    Interval,
    Offer,
    Activity,
    Title
  },
  data () {
    return {
      offerData: offerData,
      activityData: activityData,
      infoData: {},
      web3: {},
      ERC20Contract: null,
      makerOrder: null,
      countdownData: 0, // 倒计时
      characteristic: [], // 特点
      showDesc: true, // 描述信息编辑开关
      description: '--', // 描述信息
      timer: null,
      ownerFlag: false, // 是否是拥有者
      isSell: false // 是否已经挂售
    }
  },
  created () {
    this.web3 = initWeb3()
    console.log(initContract(), this.web3, contractAddress) // 合约初始化
    this.ERC20Contract = initContract().ERC20Contract
    console.log(this.ERC20Contract)
    // this.$toast.show(0)
    // this.$toast.show(1)
    // this.$toast.show(2)
    // this.$toast.show(3)
    // this.$toast.show(4)
    // this.$toast.show(5)
    // if (window.ethereum) {
    //   this.web3 = new Web3(window.ethereum)
    //   // console.log(web3)
    // }
    this.getDetails()
  },
  watch: {
    showDesc: function (newVal, oldVal) {
      if (newVal === false) {
        this.getDescInfoFocus()
      }
    }
  },
  methods: {
    getDomainSep: async function (_name, contractAddr) {
      var name = this.web3.utils.soliditySha3(_name)
      console.log('name: ', name)
      var version = this.web3.utils.soliditySha3({
        type: 'string',
        value: '1'
      })
      var typeHash = this.web3.utils.soliditySha3(
        'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'
      )
      console.log('typeHash: ', typeHash)
      // var chain_id = web3.eth.getChainId()
      var chain_id = await this.web3.eth.getChainId()
      console.log('chain id:', chain_id)
      var domainSeparator = this.web3.utils.soliditySha3(
        { t: 'bytes32', v: typeHash },
        { t: 'bytes32', v: name },
        { t: 'bytes32', v: version },
        { t: 'uint256', v: chain_id },
        { t: 'uint256', v: contractAddr }
      )
      console.log('domainSeparator:', domainSeparator)
      return domainSeparator
    },
    hundleSellSubmit: async function () {
      this.$router.replace({
        path: '/sell',
        query: {
          artId: this.$route.query.artId
        }
      })
    },
    hundleSell: async function () {
      this.$router.replace({
        path: '/sell'
      })
      const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000'
      const user = '0xb6b9067C1106CfDC0Bd457C71211CB14F51E8f3F'
      const isOrderAsk = 1
      const signer = user
      const collection = '0x0000000000000000000000000000000000000000'
      const price = 101
      const tokenId = 1
      const amount = 1
      const strategy = '0xE926E1BFDfC441bf9f6f9aE998677f3eaD9aCC8F'
      const currency = '0xdAC17F958D2ee523a2206206994597C13D831ec7'
      const nonce = 0
      // const startTime = Math.floor(Date.now() / 1000) - 100
      const startTime = 1651739181
      // const endTime = Math.floor(Date.now() / 1000) + 1000
      const endTime = 1651740281
      const minPercentageToAsk = 9000
      var Params = ZERO_ADDRESS
      var paramsHash = this.web3.utils.soliditySha3(Params)
      const MAKER_ORDER_HASH =
        '0x40261ade532fa1d2c7293df30aaadb9b3c616fae525a0b56d3d411c841a85028'
      console.log('paramsHash: ', paramsHash)
      var typeHash = this.web3.utils.soliditySha3(
        'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'
      )
      console.log('typeHash: ', typeHash)
      var hashMsg = this.web3.utils.soliditySha3(
        {t: 'bytes32', v: MAKER_ORDER_HASH},
        {t: 'uint256', v: isOrderAsk},
        {t: 'bytes32', v: signer},
        {t: 'bytes32', v: collection},
        {t: 'uint256', v: price},
        {t: 'uint256', v: tokenId},
        {t: 'uint256', v: amount},
        {t: 'bytes32', v: strategy},
        {t: 'bytes32', v: currency},
        {t: 'uint256', v: nonce},
        {t: 'uint256', v: startTime},
        {t: 'uint256', v: endTime},
        {t: 'uint256', v: minPercentageToAsk},
        {t: 'bytes32', v: paramsHash}
      )
      console.log('hashMsg:', hashMsg)
      // var domainSeparator = await this.getDomainSep(
      //   "ImeetNFT",
      //   "0xb0bBE46c1DE451B8de86E104B730F2Ca7F64aB93"
      // );
      // var hashs = this.web3.utils.soliditySha3(
      //   "\x19\x01",
      //   domainSeparator,
      //   hashMsg
      // );
      // console.error(hashs);

      const msgParams = JSON.stringify({
        domain: {
          chainId: 1337,
          name: 'ImeetNFT',
          verifyingContract: '0x45894a025dfA7D73043556A9137E395f870d5490',
          version: '1'
        },
        message: {
          orderhash: hashMsg
        },
        primaryType: 'OrderHash',
        types: {
          EIP712Domain: [
            { name: 'name', type: 'string' },
            { name: 'version', type: 'string' },
            { name: 'chainId', type: 'uint256' },
            { name: 'verifyingContract', type: 'address' }
          ],
          OrderHash: [
            {name: 'orderhash', type: 'bytes32'}
          ]
        }
      })

      console.log(msgParams)
      // console.error(hashs)

      var from = this.$cookies.get('wallet_acount')

      // this.web3.eth.sign(from, hashs, function (err, result) {
      //   if (err) return console.error(err);
      //   console.log("SIGNED:" + result);
      // });

      // 使用eth_sign裸方法，直接对最终哈希签名，metamask会提示该方法不安全
      // var params = [from, hashs];
      // var method = "eth_sign";
      // console.log(from, params, method, ";;;;;");
      // 使用eth_signTypedData_V4结构化签名方法，这里只对最终哈希结构化
      var params = [from, msgParams]
      var method = 'eth_signTypedData_v4'
      console.log(from, params, method, ';;;;;')

      this.web3.currentProvider.sendAsync(
        { method, params, from },
        (err, result) => {
          console.log(err, result, 'currentProvider')
          if (result) {
            this.makerOrder = {
              isOrderAsk: isOrderAsk,
              signer: signer,
              collection: collection,
              price: price,
              tokenId: tokenId,
              amount: amount,
              strategy: strategy,
              currency: currency,
              nonce: nonce,
              startTime: startTime,
              endTime: endTime,
              minPercentageToAsk: minPercentageToAsk,
              params: params,
              signature: result
            }
          }
          this.ApproveSubmit()
        }
      )
    },
    ApproveSubmit: async function() {
      await this.ERC20Contract.methods
        .approve(contractAddress.ERC20Address, 101)
        .send({from: this.$cookies.get('wallet_acount')}, (err, res) => {
          console.log(err, res, 'approve')
          if (res) {
          } else {
            console.log('approve.err:' + err)
          }
        })
    },
    edit: function (e) {
      this.showDesc = !this.showDesc
    },
    confirm: function () {
      this.showDesc = !this.showDesc
    },
    onAndOff: function (val) {
      this.showDesc = val
    },
    /**
     * 查询艺术品详情
     * @param {id} 艺术品ID
    */
    getDetails: function () {
      this.$loading.show()
      const params = {
        id: this.$route.query.artId
      }
      this.$Api.Collection.getCollectionArtDetail(params)
        .then((res) => {
          this.$loading.hide()
          console.log(res, 'getDetails', JSON.stringify(res))
          if (res && res.code === 200) {
            this.infoData = res.data.asset
            const decoded = decodeURI(atob(this.infoData.Metadata))
            this.characteristic = JSON.parse(decoded)
            this.description = this.infoData.Description
            this.countdownData = res.data.makerOrder.EndTime
            if (this.infoData.HoldAddress === this.$cookies.get('wallet_acount')) {
              this.ownerFlag = true
            } else {
              this.ownerFlag = false
            }
            if (res.data.makerOrder.ID === 0) {
              this.isSell = false
            } else {
              this.isSell = true
            }
            // console.log(this.infoData, res.data)
            console.log(this.isSell, 'this.ownerFlag:', this.ownerFlag)
          }
        })
        .catch((err) => {
          this.$loading.hide()
          console.log(err, 'getDetails', JSON.stringify(err))
        })
    },
    // 编辑描述信息失焦事件
    changeDescBlur: function () {
      this.showDesc = !this.showDesc
      clearInterval(this.timer)
      this.updateDescInfo()
    },
    // 更新描述信息
    updateDescInfo: function () {
      this.$loading.show()
      const params = {
        id: Number(this.$route.query.artId),
        image_url: this.infoData.image_url,
        name: this.infoData.name,
        description: this.description,
        public_chain_id: this.infoData.public_chain_id,
        scheme_id: this.infoData.scheme_id,
        class_id: this.infoData.class_id,
        hold_number: this.infoData.hold_number,
        metadata: this.infoData.Metadata
      }
      this.$Api.Works.changeArtWorksDesc(params)
        .then((res) => {
          this.$loading.hide()
          console.log(res, 'changeArtWorksDesc', JSON.stringify(res))
          if (res && res.code === 200) {
          }
        })
        .catch((err) => {
          this.$loading.hide()
          console.log(err, 'changeArtWorksDesc', JSON.stringify(err))
        })
    },
    // 编辑聚焦事件
    getDescInfoFocus: function () {
      this.timer = setInterval(() => {
        this.$refs.inputRef.focus()
      }, 0)
    }
  }
}
</script>
<style lang="less" scoped>
.superBox {
  width: 100%;
  height: auto;
  overflow: hidden;
  .superMain {
    width: 70%;
    height: auto;
    overflow: hidden;
    padding-bottom: 100px;
    .describe_p {
      height:100px;
      overflow-y: scroll;
      word-break: normal;
      white-space: pre-wrap;
      word-wrap:break-word;
    }
    .textBox {
      /deep/.el-textarea__inner {
        background: none;
        color: #fff;
        box-sizing: border-box;
        border: 3px dashed #323232;
      }
    }
    .btn {
      margin-top: 24%;
    }
    .btn {
      /deep/.el-button--primary {
        width: 45%;
        border: 0;
      }
      /deep/.el-button--primary:focus,
      .el-button--primary:hover {
        background: #a0f4f7;
        color: #000;
        border: 0;
      }
    }
  }
}
</style>
